package com.xxx.services.impl;

import com.xxx.common.AppResult;
import com.xxx.common.ResultCode;
import com.xxx.dao.UserMapper;
import com.xxx.exception.ApplicationException;
import com.xxx.model.Board;
import com.xxx.model.User;
import com.xxx.services.IUserService;
import com.xxx.utils.MD5Util;
import com.xxx.utils.StringUtil;
import com.xxx.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //1. 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2. 按用户名查询用户信息
        User existUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if (existUser != null) {
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //3. 新增用户流程, 设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //4. 写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        log.info("新增用户成功, username = " + user.getUsername());

    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = selectByUserName(username);
        //用户不存在
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + "username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //对密码进行校验
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        log.info("登陆成功, username: " + username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByPrimaryKey(id);

    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id == 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.info(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的帖子数量
        User updateUser = new User();//重新创建一个用来更新的类
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }


    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id == 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.info(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的帖子数量
        User updateUser = new User();//重新创建一个用来更新的类
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        if(user.getArticleCount() < 0){
            user.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if(user == null || user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //定义一个标志位, 校验所有的参数是否同时为空
        boolean checkAttr = false;
        //用于更新的对象, 防止用户传入其他属性, 覆盖了没有经过校验的字段
        User updateUser = new User();
        updateUser.setId(user.getId());

        //对每一个参数进行校验, 并赋值
        //校验userName

        if(!StringUtil.isEmpty(user.getUsername()) && !existsUser.getUsername().equals(user.getUsername())){
            //需要更新用户名, 进行唯一性校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser != null && checkUser.getId() != user.getId()){
                //用户已经存在
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //可以修改
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        //校验nickName
        if(user.getNickname() != null) {
            if(!StringUtil.isEmpty(user.getNickname()) && !user.getNickname().equals(existsUser.getNickname())) {
                //可以修改
                updateUser.setNickname(user.getNickname());
                checkAttr = true;
            }
        }
        //校验gender
        if(user.getGender() != null && user.getGender() != existsUser.getGender()){
            //可以修改
            updateUser.setGender(user.getGender());
            checkAttr = true;
        }
        //校验email
        if(user.getEmail() != null) {
            if( !StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(existsUser.getEmail())) {
                //可以修改
                updateUser.setEmail(user.getEmail());
                checkAttr = true;
            }
        }
        //校验phoneNum
        if(user.getPhoneNum() != null ){
            if(!StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existsUser.getPhoneNum())){
                //可以修改
                updateUser.setPhoneNum(user.getPhoneNum());
                checkAttr = true;
            }
        }
        //校验Remark
        if(user.getRemark() != null ) {
            if (!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(existsUser.getRemark())) {
                //可以修改
                updateUser.setRemark(user.getRemark());
                checkAttr = true;
            }
        }
        //根据标志位决定是否执行更新
        if(!checkAttr) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed("请输入要修改的内容"));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if(id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码
        //对老密码进行加密, 获取密文
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if(!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //生成新的盐值
        String salt = UUIDUtil.UUID_32();
        //生成新密码的密文
        String encryptPassword = MD5Util.md5Salt(newPassword, salt);

        //构造要更新的对象
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(encryptPassword);
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(new Date());

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
